import { Modal, Spin } from 'antd'
import './style.less'

// showLoading的参数类型
interface loadingConfig {
  from: string
  text: string
}

// 字面量类型
type modalType = 'error' | 'confirm' | 'warning' | 'success' | 'info'

// showModal的参数类型
interface modalConfig {
  title?: string
  content?: string
  okText?: string
  onOk?: () => void
}

/**
 * 统计有多少个loading请求
 */
const loadingCount = (function () {
  let count = 0
  return {
    add(): number {
      count += 1
      return count
    },
    reduce(): number {
      count && (count -= 1)
      return count
    },
  }
})()

let spinModal: any

export function showModal(type: modalType = 'info', config: modalConfig) {
  console.log('$$$$$$$$$$$$$$$$$$$$$$$')
  Modal.info({
    className: 'tips',
    title: config.title || '系统提示',
    ...config,
  })
}

export function hideModal() {}

export function showLoading(config: loadingConfig) {
  // 请求数+1
  loadingCount.add()
  const content = {
    className: 'spin',
    content: <Spin tip={config?.text ?? '加载中...'} />,
  }
  // 显示loading
  if (!spinModal) {
    spinModal = Modal.info(content)
  } else {
    spinModal.update(content)
  }
}

export function hideLoading() {
  // 所有使用了全局loading的请求完成后才消失
  if (loadingCount.reduce() === 0) {
    // 避免网速太快造成闪屏，这里延迟200ms后才销毁
    setTimeout(() => {
      spinModal.destroy()
    }, 200)
  }
}

export function reLoading() {
  Modal.warn({
    className: 'tips re-loading',
    title: '系统消息',
    content: '您还未登陆或登陆已过期，点击后重新登陆',
    onOk() {
      window.location.href = `/login?redirect=${window.location.pathname}`
    },
    okText: '登陆',
  })
}

export function ajaxError<T>(message: T[]) {
  Modal.warn({
    className: 'tips ajax-error',
    title: '系统消息',
    content: message.map(item => <div>{item}</div>),
  })
}

export function toast() {}
